package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.Lists;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.TemporaryStaffAccount;
import com.ruoyi.system.domain.TemporaryStaffAccountCertificate;
import com.ruoyi.system.entity.SysRemind;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.TemporaryStaffAccountCertificateMapper;
import com.ruoyi.system.mapper.TemporaryStaffAccountMapper;
import com.ruoyi.system.service.SysRemindService;
import com.ruoyi.system.service.TemporaryStaffAccountCertificateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 临时施工人员证书信息(TemporaryStaffAccountCertificate)表服务实现类
 *
 * @author makejava
 * @since 2023-06-06 14:08:36
 */
@Slf4j
@Service("temporaryStaffAccountCertificateService")
public class TemporaryStaffAccountCertificateServiceImpl implements TemporaryStaffAccountCertificateService {
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysRemindService sysRemindService;
    @Resource
    private EnterpriseWXServiceImpl enterpriseWXService;
    @Resource
    private TemporaryStaffAccountMapper temporaryStaffAccountMapper;
    @Resource
    private TemporaryStaffAccountCertificateMapper temporaryStaffAccountCertificateDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public TemporaryStaffAccountCertificate queryById(Integer id) {
        return this.temporaryStaffAccountCertificateDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param temporaryStaffAccountCertificate 筛选条件
     * @param pageRequest                      分页对象
     * @return 查询结果
     */
    @Override
    public Page<TemporaryStaffAccountCertificate> queryByPage(TemporaryStaffAccountCertificate temporaryStaffAccountCertificate, PageRequest pageRequest) {
        long total = this.temporaryStaffAccountCertificateDao.count(temporaryStaffAccountCertificate);
        return new PageImpl<>(this.temporaryStaffAccountCertificateDao.queryAllByLimit(temporaryStaffAccountCertificate, pageRequest), pageRequest, total);
    }

    @Override
    public List<TemporaryStaffAccountCertificate> queryAll(TemporaryStaffAccountCertificate temporaryStaffAccountCertificate) {
        return temporaryStaffAccountCertificateDao.queryAll(temporaryStaffAccountCertificate);
    }

    /**
     * 新增数据
     *
     * @param temporaryStaffAccountCertificate 实例对象
     * @return 实例对象
     */
    @Override
    public TemporaryStaffAccountCertificate insert(TemporaryStaffAccountCertificate temporaryStaffAccountCertificate) {
        this.temporaryStaffAccountCertificateDao.insert(temporaryStaffAccountCertificate);
        return temporaryStaffAccountCertificate;
    }

    /**
     * 修改数据
     *
     * @param temporaryStaffAccountCertificate 实例对象
     * @return 实例对象
     */
    @Override
    public TemporaryStaffAccountCertificate update(TemporaryStaffAccountCertificate temporaryStaffAccountCertificate) {
        this.temporaryStaffAccountCertificateDao.update(temporaryStaffAccountCertificate);
        return this.queryById(temporaryStaffAccountCertificate.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.temporaryStaffAccountCertificateDao.deleteById(id) > 0;
    }

    @Override
    public Map<Integer, List<TemporaryStaffAccountCertificate>> mateCertificate(TemporaryStaffAccountCertificate temporaryStaffAccountCertificate) {
        List<TemporaryStaffAccountCertificate> temporaryStaffAccountCertificates = temporaryStaffAccountCertificateDao.mateCertificate(temporaryStaffAccountCertificate);
        if (CollectionUtils.isEmpty(temporaryStaffAccountCertificates)) {
            return new HashMap<>();
        }

        List<TemporaryStaffAccountCertificate> temporaryStaffAccountCertificatesResp = new ArrayList<>();
        //过滤掉有效期小于今天的数据
        for (TemporaryStaffAccountCertificate var : temporaryStaffAccountCertificates) {
            String remind = var.getPeriodEnd();
            Date date = new Date();
            boolean after = date.after(DateUtils.parseDate(remind));
            if (!after) {
                temporaryStaffAccountCertificatesResp.add(var);
            }
        }

        return temporaryStaffAccountCertificatesResp.stream().collect(Collectors.groupingBy(TemporaryStaffAccountCertificate::getPid));
    }

    @Override
    public String importExcel(List<TemporaryStaffAccountCertificate> temporaryStaffAccountCertificates, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(temporaryStaffAccountCertificates)
                || temporaryStaffAccountCertificates.isEmpty()) {
            throw new ServiceException("导入用户数据不能为空！");
        }

        Map<Integer, List<TemporaryStaffAccountCertificate>> collect = null;
        List<TemporaryStaffAccountCertificate> saveList = Lists.newArrayList();

        List<TemporaryStaffAccount> temporaryStaffAccounts = temporaryStaffAccountMapper.queryAll(new TemporaryStaffAccount());

        Map<String, TemporaryStaffAccount> initMap = temporaryStaffAccounts.stream()
                .collect(Collectors.toMap(TemporaryStaffAccount::getCardNumber, el -> el, (e1, e2) -> e1));

        List<TemporaryStaffAccountCertificate> staffAccountCertificates =
                temporaryStaffAccountCertificateDao.queryAll(new TemporaryStaffAccountCertificate());

        if (!CollectionUtils.isEmpty(staffAccountCertificates)) {
            collect = staffAccountCertificates.stream()
                    .collect(Collectors.groupingBy(TemporaryStaffAccountCertificate::getPid));
        }

        for (TemporaryStaffAccountCertificate var : temporaryStaffAccountCertificates) {
            TemporaryStaffAccount temporaryStaffAccount = initMap.get(var.getCardNumber());
            var.setPid(temporaryStaffAccount.getId());
        }

        for (TemporaryStaffAccountCertificate var : temporaryStaffAccountCertificates) {
            if (null != collect && collect.containsKey(var.getPid())) {
                List<TemporaryStaffAccountCertificate> accountCertificates = collect.get(var.getPid());
                Map<String, List<TemporaryStaffAccountCertificate>> collected = accountCertificates.stream()
                        .collect(Collectors.groupingBy(TemporaryStaffAccountCertificate::getCertificateCode));
                if (collected.containsKey(var.getCertificateCode())) {
                    continue;
                }
            }

            log.info("身份证号 + {}", var.getCardNumber());
            TemporaryStaffAccount temporaryStaffAccount = initMap.get(var.getCardNumber());
            TemporaryStaffAccountCertificate temporaryStaffAccountCertificate = new TemporaryStaffAccountCertificate();
            BeanUtils.copyBeanProp(temporaryStaffAccountCertificate, var);

            log.info("当前pid码 + {}", temporaryStaffAccount.getId());
            temporaryStaffAccountCertificate.setPid(temporaryStaffAccount.getId());
            saveList.add(temporaryStaffAccountCertificate);
        }

        if (CollectionUtils.isEmpty(saveList)) {
            return
                    "导入成功" + 0 + "条";
        }

        temporaryStaffAccountCertificateDao.insertBatch(saveList);
        return "导入成功" + saveList.size() + "条";
    }

    @Scheduled(cron = "0 0 8 * * ?")
    public void sendTemporaryStaffAccountCertificate() {
        List<TemporaryStaffAccountCertificate> temporaryStaffAccountCertificates = temporaryStaffAccountCertificateDao.queryAll(new TemporaryStaffAccountCertificate());
        if (CollectionUtils.isEmpty(temporaryStaffAccountCertificates)) {
            return;
        }

        Date date = new Date();
        for (TemporaryStaffAccountCertificate var : temporaryStaffAccountCertificates) {
            String remindDate = var.getRemindDate();
            if (StringUtils.isEmpty(remindDate)) {
                continue;
            }

            boolean after = date.after(DateUtils.parseDate(remindDate));
            if (after) {
                SysUser selectUserById = sysUserMapper.getVidInfo(Long.valueOf(var.getPid()));
                String stringBuffer = "姓名:" + selectUserById.getUserName() + "证书编号:" + var.getCertificateCode() + "即将到期。";

               /* SysUser sysUser = new SysUser();
                sysUser.setNickName(var.getRecordName());
                List<SysUser> sysUsers = sysUserMapper.selectWxIdByNickName(sysUser);
                if (CollectionUtils.isEmpty(sysUsers)) {
                    continue;
                }

                SysUser user = sysUsers.stream().findFirst().orElse(new SysUser());*/

                //  sendMessageRequest.setTouser(CollUtil.join(userIds, "|"));
                SysRole sysRole = new SysRole();
                sysRole.setRoleKey("grzzts");
                List<SysUser> sysUsers = sysUserMapper.selectUserByRoleName(sysRole);
                if (CollectionUtils.isEmpty(sysUsers)) {
                    continue;
                }

                for (SysUser sys : sysUsers) {
                    sysRemindService.insert(SysRemind.TYPE_PROMPT, stringBuffer, sys.getUserId().intValue());
                }

                List<String> collect = sysUsers.stream().map(SysUser::getWxUserId).collect(Collectors.toList());
                EnterpriseWXServiceImpl.SendMessageRequest sendMessageRequest = new EnterpriseWXServiceImpl.SendMessageRequest();
                sendMessageRequest.setTouser(CollUtil.join(collect, "|"));
                sendMessageRequest.setMsgtype("text");
                sendMessageRequest.setAgentid(1000319);
                EnterpriseWXServiceImpl.MessageContent messageContent = new EnterpriseWXServiceImpl.MessageContent();
                messageContent.setContent(stringBuffer);
                sendMessageRequest.setText(messageContent);
                enterpriseWXService.pushMessage(sendMessageRequest);

            }
        }
    }

}
